package com.ysh.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ysh.common.ResultFactory;
import com.ysh.exception.BusinessException;
import com.ysh.mapper.UserMapper;
import com.ysh.pojo.User;
import com.ysh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 用户业务层接口实现类
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    // 依赖注入
    @Autowired
    UserMapper userMapper;

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @Override
    public boolean addUser(User user) {
        return userMapper.addUser(user);
    }

    /**
     * 删除用户信息
     *
     * @param uuid 用户id
     * @return
     */
    @Override
    public boolean deleteUser(Integer uuid) {
        return userMapper.deleteUser(uuid);
    }

    /**
     * 修改用户信息
     *
     * @param user 用户对象
     * @return
     */
    @Override
    public boolean updateUser(User user) {
        return userMapper.updateUser(user);
    }

    /**
     * 多条件模糊查询搜索，带分页
     *
     * @param user 多条件封装对象
     * @param page 当前页
     * @param size 每页记录数
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Page<User> getUsers(User user, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        Page<User> users = (Page<User>) userMapper.getUsers(user);

        return users;
    }

    /**
     * 查询单个用户信息
     *
     * @param uuid id编号
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public User findById(Integer uuid) {
        return userMapper.findById(uuid);
    }

    /**
     * 带分页查询所有用户信息
     *
     * @param page 当前页
     * @param size 每页记录数
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Page<User> findAll(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        Page<User> all = (Page<User>) userMapper.findAll();
        return all;
    }

    /**
     * 根据用户名和密码登录
     *
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public User login(String userName, String password) {
        if (StringUtils.isEmpty(userName)){
            throw new BusinessException(ResultFactory.ERROR("用户名不能为空！"));
        }
        if (StringUtils.isEmpty(password)){
            throw new BusinessException(ResultFactory.ERROR("密码不能为空！"));
        }

        User user = userMapper.getByUserNameAndPassword(userName,password);
        if (user == null){
            throw new BusinessException(ResultFactory.ERROR("用户名或密码错误！"));
        }
        return user;
    }
}
